<template>
	<view class="tabContent" v-show="true">
		<view class="param-title">基本信息</view>
		<view class="param-item">
			<label>姓名</label>
			<text class="text">{{ userInfo.nickName }}</text>
		</view>
		<view class="paramBox">
			<view class="param-title">考试信息</view>
			<view class="param-item">
				<label>年级</label>
				<text class="text">{{ examInfo.stage }}{{ examInfo.grade }}({{ examInfo.term }})</text>
			</view>
			<view class="param-item">
				<label>考试名称</label>
				<text class="text">{{ examInfo.examList[examIndex].examName }}</text>
			</view>
			<view class="param-item">
				<label>考试日期</label>
				<text class="text">{{ examInfo.examList[examIndex].examDate }}</text>
			</view>

			<!-- 根据年级获取对应的科目列表并循环展示科目输入框，添加key绑定，确保唯一性和高效更新 -->
			<view v-for="(subject, subjectIndex) in examInfo.examList[examIndex].scoreList" :key="subjectIndex">
				<view class="param-item-2">
					<label>{{ subject.name }}</label>
					<uni-easyinput :inputBorder='false' :value="subject.score" type="digit" maxlength="4"
						:styles="{color: '#2979FF',}" placeholder='请输入分数'
						@input="handleSubjectScoreChange($event, subjectIndex)">
					</uni-easyinput>
					<label>满分</label>
					<uni-easyinput :inputBorder='false' :value="subject.full" type="digit" maxlength="4"
						:styles="{color: '#ff007f',}" placeholder='请输入满分值'
						@input="handleSubjectFullChange($event, subjectIndex)">
					</uni-easyinput>
				</view>
			</view>

			<view class="param-title">排名信息</view>
			<view class="param-item">
				<label>班级排名</label>
				<uni-easyinput prefixIcon="hand-up-filled" :inputBorder='false'
					v-model="examInfo.examList[examIndex].class_rank" type="number" maxlength="3"
					:placeholderStyle="placeholderStyle" placeholder='请输入班级排名' @input="handleClassRankChange">
				</uni-easyinput>
			</view>
			<view class="param-item">
				<label>学校排名</label>
				<uni-easyinput prefixIcon="hand-up-filled" :inputBorder='false'
					v-model="examInfo.examList[examIndex].school_rank" type="number" maxlength="4"
					:placeholderStyle="placeholderStyle" placeholder='请输入学校排名' @input="handleSchoolRankChange">
				</uni-easyinput>
			</view>
		</view>
		<!-- 隔离与按钮直接的间隔 -->
		<view style="height: 30rpx;"></view>
		<view>
			<button class="button" type="primary" @click="saveStudentInfo">保存</button>
		</view>
	</view>
</template>

<script>
	import {
		reactive,
		onMounted,
		watch,
		toRefs,
	} from 'vue';
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app';
	import useStudentStore from '@/store/studentStore.js';
	import moment from 'moment';
	import {
		defaultSubjects,
		defaultGradeColumn,
		defaultGradeSubjectOption
	} from '@/utils/enum';
	import {
		string
	} from '../../uni_modules/uview-plus/libs/function/test';

	// 在这里将gradeSubjectMap提升为全局变量，初始化为一个空的Map
	const gradeSubjectMap = new Map();

	export default {
		props: {
			examInfoIndex: {
				type: Number,
				required: true
			},
			examIndex: {
				type: Number,
				required: true
			}
		},
		components: {},
		setup(props) {
			///在方法内调用，否则真机运行有问题
			const studentStore = useStudentStore();
			studentStore.setStudents(studentStore.students);
			const placeholderStyle = "color:#000000;font-size:14px;font-weight:546;";
			const gradeList = defaultGradeColumn;
			// 响应式数据
			const state = reactive({
				userInfo: {},
				examInfo: {
					stage: '',
					grade: '',
					term: '',
					examList: {
						examName: '',
						examDate: '',
						scoreList: [],
						class_rank: '',
						school_rank: ''
					},
				}

			});

			const examInfoIndex = Number(props.examInfoIndex);
			const examIndex = Number(props.examIndex);
			// 加载用户信息
			const loadUserInfoAsync = async (id) => {
				const student = studentStore.findStudent(id);
				console.log('loadUserInfoAsync student', student)
				if (student) {
					state.userInfo = student;
					// 根据传入的索引获取对应的考试信息并赋值给examList
					if (examInfoIndex !== undefined && examIndex !== undefined) {
						state.examInfo = state.userInfo.examInfo[examInfoIndex];
					}
					console.log('state.examInfo', state.examInfo)
					console.log('state.userInfo', state.userInfo)
					return state.userInfo;
				} else {
					console.error(`未找到id为${id}的学生信息`);
				}

			};

			// 处理科目分数输入变化
			const handleSubjectScoreChange = (e, subjectIndex) => {
				console.log('handleSubjectScoreChange state.examInfo', state.examInfo);
				const _subjects = state.examInfo.examList[examIndex].scoreList;
				const subjectScoreItem = _subjects[subjectIndex];
				if (subjectScoreItem) {
					// 备份原始分数值
					const originalScore = subjectScoreItem.score;
					const inputScore = parseFloat(e);
					const fullScore = parseFloat(subjectScoreItem.full);
					if (isNaN(inputScore)) {
						return;
					}
					if (!isNaN(fullScore) && inputScore >= 0 && inputScore <= fullScore) {
						subjectScoreItem.score = inputScore;
					} else {
						uni.showToast({
							title: `输入的${subjectScoreItem.name}分数超过满分${fullScore}，请输入有效数字`,
							icon: 'none', //'none' 表示只显示文字提示，也可其他图标如 'success'、'error'等
							duration: 3000 // 提示显示的时长，单位为毫秒，这里设置为 2 秒
						});
						// 使用备份的原始分数值恢复
						subjectScoreItem.score = originalScore;
						subjectScoreItem.full = fullScore;
						console.log('subjectScoreItem.score', subjectScoreItem.score)
					}
				} else {
					console.warn(`未找到名为${subjectScoreItem.name}的科目对应的分数项，请检查数据`);
				}
			};

			// 处理科目满分输入变化
			const handleSubjectFullChange = (e, subjectIndex) => {
				console.log('handleSubjectFullChange state.examInfo', state.examInfo)
				const _subjects = state.examInfo.examList[examIndex].scoreList
				const subjectScoreItem = _subjects[subjectIndex];
				if (subjectScoreItem) {
					const inputFull = parseFloat(e);
					if (isNaN(inputFull)) {
						return
					}
					subjectScoreItem.full = Number(e)
				}
			};

			// 处理班级排名输入变化
			const handleClassRankChange = (e) => {
				const inputRank = parseInt(e);
				if (!isNaN(inputRank) && inputRank >= 0) {
					state.examInfo.examList[examIndex].class_rank = inputRank;
				} else {
					console.warn('输入的班级排名格式不正确，请输入有效数字');
					// 可以考虑将排名重置为合理的默认值等操作
				}
			};

			// 处理学校排名输入变化
			const handleSchoolRankChange = (e) => {
				const inputRank = parseInt(e);
				if (!isNaN(inputRank) && inputRank >= 0) {
					state.examInfo.examList[examIndex].school_rank = inputRank;
				} else {
					console.warn('输入的学校排名格式不正确，请输入有效数字');
					// 可以考虑将排名重置为合理的默认值等操作
				}
			};

			// 保存学生信息
			const saveStudentInfo = () => {
				const {
					examName,
					examDate,
					scoreList,
					class_rank,
					school_rank
				} = state.examInfo.examList[examIndex];

				if (scoreList.some(s => s.score === '' || s.full === '')) {
					console.warn('请填写所有科目的考试分数');
					return;
				}
				if (!class_rank) {
					console.warn('班级排名不能为空');
					return;
				}
				if (!school_rank) {
					console.warn('学校排名不能为空');
					return;
				}
				// 对应examList中的位置，将修改后的数据更新回去
				state.examInfo.examList[examIndex] = {
					examName: examName,
					examDate: examDate,
					class_rank: parseInt(class_rank),
					school_rank: parseInt(school_rank),
					scoreList: scoreList
				};
				// 此处可以添加真正的保存逻辑，比如调用接口将数据发送到后端等
				console.log('数据校验通过，可进行保存操作，此处添加实际保存逻辑');
				// 调用updateExamInfo更新studentStore
				studentStore.updateExamInfo(state.userInfo.id, state.examInfo);
				console.log('after saveStudentInfo student', studentStore.studentMap.get(1));
			}

			// 在组件挂载完成时，调用updateSubjectsByGrade进行科目列表数据更新（传入初始的年级和学期数据）
			onMounted(() => {});

			// 使用正确导入的onLoad生命周期钩子，在页面加载时调用loadUserInfo(1)
			onLoad(async () => {
				console.log('进入onLoad生命周期钩子，准备加载用户信息');
				await loadUserInfoAsync(1);
				console.log('完成loadUserInfo调用');
			});

			return {
				...toRefs(state),
				gradeList,
				placeholderStyle,
				gradeSubjectMap,
				handleSubjectScoreChange,
				handleSubjectFullChange,
				handleClassRankChange,
				handleSchoolRankChange,
				saveStudentInfo
			};
		}
	};
</script>

<style lang="scss" scoped>
	.tabContent {
		padding-top: 10rpx;
		background: #fff;
		overflow: hidden;
	}

	.param-title {
		background: #f5f5f5;
		height: 80rpx;
		line-height: 80rpx;
		margin: 10rpx 30rpx 0;
		font-size: 28rpx;
		text-indent: 30rpx;
	}

	.param-item {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f5f5f5;
		border-left: 1rpx solid #f5f5f5;
		border-right: 1rpx solid #f5f5f5;
		margin: 0 30rpx;
		padding: 0 30rpx;
		display: flex;
	}

	.param-item label {
		width: 260rpx;
		color: #999;
	}

	.param-item-2 {
		width: 92%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f5f5f5;
		border-left: 1rpx solid #f5f5f5;
		border-right: 1rpx solid #f5f5f5;
		margin-left: 30rpx;
		display: flex;
	}

	.param-item-2 label {
		margin-left: 30rpx;
		margin-right: 30rpx;
		color: #999;
	}

	.button {
		width: 85%;
		font-size: 28rpx;
		font-weight: 550;
		border-style: hidden;
		margin-right: 30rpx;
	}

	.text {
		font-size: 28rpx;
		font-weight: 550;
		color: #a8a8a8;
	}

	.picker {
		width: 100%;
		/* 设置宽度为整行宽度 */
		height: 80rpx;
		/* 可根据实际情况调整高度，保持和其他 param-item 一致 */
		line-height: 80rpx;
		font-size: 24rpx;
		display: flex;
		justify-content: flex-start;
		/* 将文本和展开图标两端对齐 */
		align-items: center;
		/* 垂直居中 */
		position: relative;
		/* 为了设置伪元素的定位 */
		padding-left: 110rpx;
	}

	.picker::after {
		content: "";
		position: absolute;
		right: 15rpx;
		/* 根据需要调整右侧距离，设置展开图标的位置 */
		top: 40%;
		width: 20rpx;
		height: 20rpx;
		border-top: 2rpx solid #999;
		border-right: 2rpx solid #999;
		transform: rotate(45deg);
	}
</style>